package cn.achao.csr.zfb.core.config;

import cn.achao.csr.base.constant.AliConstants;
import com.alipay.api.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "csr.alipay")
public class AliConfigProperties {

    // 环境（沙箱或生产）
    private String env;

    // 沙箱环境的配置
    private CsrAlipayConfig sandbox;

    // 生产环境的配置
    private CsrAlipayConfig prod;

    /**
     * 根据环境获取配置
     * @return
     */
    @Bean
    public CsrAlipayConfig getCurrentConfig() {
        if (AliConstants.SANDBOX.equalsIgnoreCase(env)) {
            return sandbox;
        }
        return prod;
    }
    @Bean
    public AlipayClient alipayClient() throws AlipayApiException {
        AlipayConfig alipayConfig = new AlipayConfig();
        CsrAlipayConfig config = this.getCurrentConfig();
        //设置网关地址
        alipayConfig.setServerUrl(config.getGatewayUrl());
        //设置应用Id
        alipayConfig.setAppId(config.appId);
        //设置应用私钥
        alipayConfig.setPrivateKey(config.getMerchantPrivateKey());
        //设置请求格式，固定值json
        alipayConfig.setFormat(AlipayConstants.FORMAT_JSON);
        //设置字符集
        alipayConfig.setCharset(AlipayConstants.CHARSET_UTF8);
        //设置支付宝公钥
        alipayConfig.setAlipayPublicKey(config.getAlipayPublicKey());
        //设置签名类型
        alipayConfig.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

        return alipayClient;
    }

    @Data
    public static class CsrAlipayConfig {
        /**
         * 域名
         */
        private String domain;
        /**
         * 应用ID
         */
        private String appId;
        /**
         * 商户PID
         */
        private String sellerId;
        /**
         * 支付宝网关
         */
        private String gatewayUrl;
        /**
         * 商户私钥
         */
        private String merchantPrivateKey;
        /**
         * 支付宝公钥
         */
        private String alipayPublicKey;
        /**
         * 加密秘钥
         */
        private String contentKey;
        /**
         * 页面跳转同步通知页面路径
         */
        private String returnUrl;
        /**
         * 服务器异步通知页面路径
         */
        private String notifyUrl;
        /**
         * 支付宝获取auth_code地址
         */
        private String authCodeUrl;
        /**
         * auth_code回调地址
         */
        private String authCodeCallbackUrl;
    }


}
